const app = getApp()
Page({
  data: {
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    src: "", 
    baidutoken: "",
    base64: "",
    msg: ""
  },


  takePhoto() {
    var that = this;
  
    const ctx = wx.createCameraContext()
    ctx.takePhoto({
      quality: 'high',
      success: (res) => {
        this.setData({
          src: res.tempImagePath 
        })
        
        wx.getFileSystemManager().readFile({
          filePath: this.data.src, 
          encoding: 'base64', 
          success: res => { 
            this.setData({
              base64: res.data
            })
          }
        })
        this.getBaiduToken();
      } 
    }) 

    
    wx.showToast({
      title: '请重试',
      icon: 'loading',
      duration: 500
    })
  },
  error(e) {
    console.log(e.detail)
  },

  getBaiduToken() {
    var that = this;
    //acess_token获取
    wx.request({
      url: 'https://aip.baidubce.com/oauth/2.0/token', 
      data: {
        grant_type: 'client_credentials',
        client_id: 'W3GwBYFDXNj1M0AY57GjGSng', 
        client_secret: 'kRYVfePdurCGBu9Kb5hxxyGNGBuyDUr5' 
      },
      header: {
        'Content-Type': 'application/json' 
      },
      success(res) {
        that.setData({
          baidutoken: res.data.access_token 
        })
        that.uploadPhoto();
      }
    })
  },

  uploadPhoto() {
    var that = this;
    //上传人脸进行注册
    wx.request({
      url: 'https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/add?access_token=' + this.data.baidutoken,
      method: 'POST',
      data: {
        image: this.data.base64,
        image_type: 'BASE64',
        group_id: '26575168', 
        user_id: 'hao_002' 
      },
      header: {
        'Content-Type': 'application/json' 
      },
      success(res) {
        that.setData({
          msg: res.data.error_msg
        })
        
        if (that.data.msg == "pic not has face") {
          wx.showToast({
            title: '未捕获到人脸',
            icon: 'error',
          })
        }
        if (that.data.msg == 'SUCCESS') {
          wx.showToast({
            title: '人脸录入成功',
            icon: 'success',
          })
        }
      }
    })
  },
})
